<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
namespace app\tcms\controller;
use \tpfcore\Core;
use think\Db;
use think\Request;
class Upload extends Auth
{
    public function uploadimg(){
        config("default_return_type","json");
        if(request()->file()){
            $request = Request::instance();
            $param=$request->param();
            $size=2*1024*1024; //默认为2M
            $ext='jpg,png,gif'; //默认只上传图片

            $urls=[];
            foreach ($_FILES as $key => $value) {
                if($value['error']!=0) continue;
                $file = request()->file($key);
                // 移动到框架应用根目录/public/uploads/ 目录下
                $url="/data/uploads/";
                $info = $file->validate(['size'=>$size,'ext'=>$ext])->move(ROOT_PATH . 'data' . DS . 'uploads');
                if($info){
                    // 上传成功
                    $savename = str_replace("\\","/",$info->getSaveName());
                    $url=$url_cache=$url.$savename;

                    // 头像上传处理
                    if(isset($param['action']) && $param['action']=="uploadHeadimg"){

                        $url = $this->cut_headimg($url,90,90);

                        $result = Core::loadModel("User")->updateUserInfo(['headimg'=>$url],"headimg",url("h5shop/Member/datum"));

                        unset($info);

                        @unlink(ROOT_PATH.substr($url_cache,1));

                        if($result[0]!=0){

                            @unlink(ROOT_PATH.substr($url,1));  

                            return ["code"=>40048,"msg"=>$result[1]];
                        }

                    }

                    $urls[]=$url;
                }else{
                    // 上传失败获取错误信息
                    return ["code"=>"40023","msg"=>$file->getError()];
                }
            }
            return ["code"=>0,"msg"=>"上传成功","url"=>$urls];
        }else{
            return ["code"=>"40024","msg"=>"没有上传的文件"];
        }
    }

    private function cut_headimg($img,$width="100",$height="100"){

        if(empty($img)) return "";

        $arr = explode(".",$img);

        $file_name = basename($img,".".end($arr))."_thumb.".end($arr);

        $image = \think\Image::open('.'.$img);

        $dir_name='./data/uploads/headimg/'.date('Ym',time());

        if(!file_exists($dir_name)){

            mkdir($dir_name,0777,true);

        }

        $image->thumb($width, $height)->save($dir_name."/".$file_name);

        return '/data/uploads/headimg/'.date('Ym',time()).'/'.$file_name;

    }
}
